<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */


namespace App\Api\Service\Order\Controllers;

use App\Eloquent\Ygt\CustomerOrder;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Message;
use App\Eloquent\Ygt\Order;
use App\Eloquent\Ygt\OrderDistribution;
use App\Eloquent\Ygt\OrderFieldCompany;
use App\Eloquent\Ygt\OrderProcess;
use App\Eloquent\Ygt\Process as ygtProcess;
use App\Engine\OrderEngine;
use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\OrderProcessCourse;
use App\Eloquent\Ygt\OrderProcessCourseLog;
use App\Engine\Func;
use \App\Engine\Process as ProcessEngine;
use App\Engine\Permission as PermissionEngine;


class ProcessController extends Controller
{
    //工单基础信息修改
    public function orderBaseModify()
    {
        $userId             = Func::getHeaderValueByName( 'userid', 0 );
        $user               = DepartmentUser::getCurrentInfo($userId);
        $isSubmit           = request('is_submit',0);
        $orderId            = request('order_id',0);
        if( !$user || !$orderId ){
            xThrow( ERR_PARAMETER );
        }
        //获取工单基础信息字段
        $companyId          = $user->company_id;
        $fieldList          = OrderFieldCompany::getActiveFieldList( $companyId );
        if($isSubmit){
            //验证提交的内容
            $data               = request()->all();
            unset($data['is_submit']);
            unset($data['is_draft']);
            unset($data['order_id']);
            $checkResult        = ProcessEngine::checkDataValue($data,$fieldList);
            if($checkResult!==true)
            {
                xThrow($checkResult);
            }
            //更新对应的数据
            $result             = Order::where('id',$orderId)->update($data);
            if($result){
                $order                  = Order::where('id',$orderId)->first();
                ////修改工单列表消息
                //获取工单基础信息
                $where = [
                    'id'=> $orderId
                ];
                $orderInfo = Order::where($where)->first()->toArray();

                //修改主工单消息
                OrderEngine::importMainOrder($orderInfo);

                //修改工序工单消息
                $where = ['order_id'=>$orderId];
                $orderProcessList = OrderProcess::where($where)->get()->toArray();
                foreach ($orderProcessList as $orderProcessRow){
                    //工序管理员工单
                    OrderEngine::importProcessManagerOrder($orderProcessRow);
                    //查看权限
                    $processId = $orderProcessRow['process_type'];
                    $orderTypeId = $orderInfo['order_type'];
                    $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 1);//1:查看;2:可写;3:分配;4:提交;5:转发
                    OrderEngine::importProcessSeeOrder($orderProcessRow,$privilegeIds);

                    $where = ['order_process_id'=>$orderProcessRow['id']];
                    $orderProcessCourseList = OrderProcessCourse::where($where)->get()->toArray();

                    foreach ($orderProcessCourseList as $orderProcessCourseRow){
                        OrderEngine::importProcessCourseOrder($orderProcessCourseRow);
                    }
                }


                return ['message'=>'成功'];
            } else {
                xThrow('数据库错误');
            }
        } else {
            //获取工单基础信息所填写的内容
            $order              = Order::where('id',$orderId)->first()->toArray();
            // 组合字段和所填写内容
            $arr                = ['is_pre'=>'0','order_id'=>$orderId];
            $result             = ProcessEngine::setDataByFieldType($order,$fieldList,$arr);

            $re = [
                'create_order_title' => '工单基础信息',
                'process_title' => '基础信息',
                'order_base_field_list' => $result,
                'button_title'=>"确认修改"
            ];
            return $re;
        }
    }
    //工单地址信息修改
    public function distributionModify()
    {
        //获取传入数据
        $orderId            = request('order_id',0);
        if(!$orderId)
        {
            xThrow( ERR_PARAMETER );
        }
        $isSubmit           = request('is_submit',0);
        if($isSubmit){
            $data           = request()->all();
            unset($data['is_submit']);
            $where          = ['order_id'=>$orderId];
//            $obj            = OrderDistribution::where($where)->first();
            $obj            = OrderDistribution::firstOrNew(['order_id'=>$orderId]);
            $obj->fill($data);
            $obj->save();
            return $obj->id;
        }else{
            xThrow( ERR_UNKNOWN );
        }
    }
    //工单工序信息修改
    public function orderProcessModify()
    {
        $userId             = Func::getHeaderValueByName( 'userid', 25 );
        $user               = DepartmentUser::getCurrentInfo($userId);
        $isSubmit           = request('is_submit',0);
        $orderProcessId     = request('order_process_id',0);

        if( !$user || !$orderProcessId ){
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $user->company_id;
        //获取工单工序所填写的内容
        $where              = ['id'=>$orderProcessId];
        $process            = OrderProcess::where($where)->first()->toArray();
        $processId          = $process['process_type'];
        $status             = $process['status'];

        $orderInfo = \App\Eloquent\Ygt\Order::where(['id'=>$process['order_id']])->first();

        if(in_array($status,[3,4]))
        {
            xThrow( '工单已开工,不能修改' );
        }
        //获取工单基础信息字段
        $fieldList          = ygtProcess::getFieldListByProcessId( $processId );
        if($isSubmit){
            //验证提交的内容
            $data               = request()->all();
            $purchase_info = [];

            unset($data['is_submit']);
            unset($data['is_draft']);
            unset($data['order_id']);
            unset($data['order_process_id']);
            unset($data['process_id']);
            unset($data['ordertype_process_id']);
            $checkResult        = ProcessEngine::checkDataValue($data,$fieldList);

            foreach($fieldList as $key=>$val){

                if($val['field_type'] == 4){
                    $data = OrderEngine::handleInput($data,$val['field_name'],$val['field_type'],'purchase_info');
                    if(isset($data['purchase_info'])){
                        $purchase_info = $data['purchase_info'];
                        unset($data['purchase_info']);
                    }
                }


                //版
                if($val['field_type'] == 17){
                    //限制-版数量想加不能超过产品数量
                    $tmpPlateBranch = json_decode(htmlspecialchars_decode($data[$val['field_name']]), true);
                    $tmpPlateNumAll = 0;

                    if(isset($tmpPlateBranch['branch']['colourplate'])){
                        foreach ($tmpPlateBranch['branch']['colourplate'] as $tmpRow){
                            $tmpPlateNumAll += $tmpRow['num'];
                        }
                    }

                    if($tmpPlateNumAll && ($tmpPlateNumAll > $orderInfo['product_num']) ){
                        return [
                            'code' => 1,
                            'message' => '版支总数量不能超过产品数量',
                        ];
                    }

                    $tmpObj = \App\Eloquent\Ygt\CreateOrderPlate::firstOrNew(['id'=>'']);
                    $tmpInsertRow = [
                        'type' => 2,
                        'relate_id' => $process['order_id'],
                        'field_name' => $val['field_name'],
                        'content' => $data[$val['field_name']],
                    ];

                    $tmpObj->fill($tmpInsertRow);
                    $tmpObj->save();
                    $createOrderPlateId = $tmpObj->id;

                    $data[$val['field_name']] = $createOrderPlateId;
                }

                //半成品
                if($val['field_type'] == 22){

                    $tmpObj = \App\Eloquent\Ygt\CreateOrderProcessProduct::firstOrNew(['id'=>'']);
                    $tmpInsertRow = [
                        'type' => 1,
                        'relate_id' => $process['order_id'],
                        'field_name' => $val['field_name'],
                        'content' => $data[$val['field_name']],
                    ];

                    $tmpObj->fill($tmpInsertRow);
                    $tmpObj->save();
                    $createOrderProcessProductId = $tmpObj->id;

                    $data[$val['field_name']] = $createOrderProcessProductId;
                }
            }

            if($checkResult!==true)
            {
                xThrow($checkResult);
            }
            //更新对应的数据
            $where              = ['id'=>$orderProcessId];
            $result             = OrderProcess::where($where)->update($data);
            //对比修改了那些内容
            $dataChange         = ProcessEngine::changeDataByFieldType($data,$fieldList);
            $processChange      = ProcessEngine::changeDataByFieldType($process,$fieldList);
            $messageContentArr  = [];
            $materialIdList = [];
            foreach($fieldList as $key=>$val)
            {
                $valFieldName   = $val['field_name'];
                if(isset($dataChange[$valFieldName]) && isset($processChange[$valFieldName]) && $processChange[$valFieldName] != $dataChange[$valFieldName])
                {
                    $valTitle               = $val['title'];
                    $tempStr                = $valTitle.'调整为'.$dataChange[$valFieldName];
                    $messageContentArr[]    = $tempStr;
                }

                //保存材料信息
                if($val['field_type'] == 4){
                    $tmpMaterialIdList = explode(',',$data[$valFieldName]);
                    foreach($tmpMaterialIdList as $tmpMaterialId){
                        if($tmpMaterialId){
                            $materialIdList[] = $tmpMaterialId;
                        }
                    }
                }


            }
            //发消息
            if($result){
                $messageContent     = implode('rnrn',$messageContentArr);
                if($messageContent){
                    $fixedMessageContent = '工序工单信息已经修改rnrn'.$messageContent;
                    ////如果工单还未派发，不需要发送消息
                    $where = ['id'=> $process['order_id']];
                    $orderInfo = Order::where($where)->first()->toArray();
                    if($orderInfo['status'] != 4){//不是未派发状态
                        $where              = ['id'=>$orderProcessId];
                        $process            = OrderProcess::where($where)->first()->toArray();
                        $where              = ['id'=>$process['order_id']];
                        $order              = Order::where($where)->first()->toArray();
                        $foreignKey         = intval($order['customer_order_id']);

                        $messageContent = "单位名称：{$order['field_name_23']}rnrn品名：{$order['product_name']}rnrn成品规格：{$order['finished_specification']}rnrn数量： {$order['product_num']}rnrn交货日期： {$order['finished_date']}";

                        //如果有材料修改，修改ygt_order_material表的数据
                        if(!empty($materialIdList)){

                            $materialIdDealList = $materialIdList;
                            $tmpOrderMaterialList = \App\Eloquent\Ygt\OrderMaterial::where(['order_process_id'=>$orderProcessId])->get();
                            if($tmpOrderMaterialList){
                                foreach ($tmpOrderMaterialList as $tmpOrderMaterialRow){
                                    if(in_array($tmpOrderMaterialRow['material_id'],$materialIdDealList)){
                                        $materialIdDealList = array_diff($materialIdDealList,[$tmpOrderMaterialRow['material_id']]);
                                    }else{
                                        $tmpOrderMaterialRow->delete();
                                    }
                                }
                            }

                            //添加新的材料
                            foreach ($materialIdDealList as $materialId){
                                $orderId = $process['order_id'];
                                $processType = $process['process_type'];
                                $orderMaterialObj  = \App\Eloquent\Ygt\OrderMaterial::firstOrNew(['id'=>'']);
                                $tmpInsertRow = [
                                    'order_id' => $orderId,
                                    'order_process_id' => $orderProcessId,
                                    'process_type' => $processType,
                                    'material_id' => $materialId,
                                    'company_id' => $companyId,
                                ];
                                $orderMaterialObj->fill($tmpInsertRow);
                                $orderMaterialObj->save();
                            }
                        }else{
                            //清空
                            \App\Eloquent\Ygt\OrderMaterial::where(['order_process_id'=>$orderProcessId])->delete();
                        }


                        ////如果材料已领，需要另外处理
                        //判断是否已有记录生成
                        $orderProcessCourseId = '';
                        $orderMaterialCourseList = \App\Eloquent\Ygt\OrderMaterialCourse::where(['order_process_id'=>$orderProcessId,'allow_delete'=>0])->get();
                        if($orderMaterialCourseList){
                            $materialIdDealCourseList = $materialIdList;
                            //判断材料是否有变动
                            foreach ($orderMaterialCourseList as $orderMaterialCourseRow){
                                if(!$orderProcessCourseId){
                                    $orderProcessCourseId = $orderMaterialCourseRow['order_process_course_id'];
                                }

                                if(in_array($orderMaterialCourseRow['material_id'],$materialIdDealCourseList)){
                                    $materialIdDealCourseList = array_diff($materialIdDealCourseList,[$orderMaterialCourseRow['material_id']]);
                                }else{
                                    $orderMaterialCourseRow->delete();
                                }
                            }

                            //添加新材料到记录中
                            foreach ($materialIdDealCourseList as $materialId){
                                $orderId = $process['order_id'];
                                $processType = $process['process_type'];

                                $orderMaterialCourseObj  = \App\Eloquent\Ygt\OrderMaterialCourse::firstOrNew(['id'=>'']);
                                $tmpInsertRow = [
                                    'order_process_id' => $orderProcessId,
                                    'order_process_course_id' => $orderProcessCourseId,
                                    'process_type' => $processType,
                                    'material_id' => $materialId,
                                    'company_id' => $companyId,
                                ];
                                $orderMaterialCourseObj->fill($tmpInsertRow);
                                $orderMaterialCourseObj->save();
                            }
                        }

                        //追加材料消息
                        $materialIdList = \App\Engine\OrderEngine::getProcessMaterialIdList($orderProcessId);
                        if (!empty($materialIdList)) {
                            $messageContent .= "工单需使用以下材料：rnrn";
                            //获取所有材料信息
                            foreach ($materialIdList as $tmpMaterialId) {
                                //获取材料信息
                                $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                                $tmpMaterialName = $tmpMaterialRow['product_name'];
                                $tmpMaterialNum = $tmpMaterialRow['number'];
                                $tmpMaterialUnit = $tmpMaterialRow['unit'];

                                $messageContent .= "{$tmpMaterialName} 【库存】{$tmpMaterialNum}（{$tmpMaterialUnit}）rnrn";
                            }
                        }

                        $messageContent.=$fixedMessageContent;

                        //给对应的工序管理员发消息
                        if($order['uid'] != $process['uid']){//如果工序管理员为下单人不发消息
                            $data           = [
                                'company_id'=>$companyId,  'privilege_id'=>'',
                                'form_user_id'=>$userId, 'to_user_id'=>$process['uid'],
                                'foreign_key'=>$foreignKey,
                                'type'=>14,'type_id'=>$process['id'],
                                'title'=>$order['order_title'],'content'=>$messageContent,
                                'theme'=>'工单详情调整'
                            ];
                            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
                        }

                        //给有查看权限的用户
                        //给此步骤有查看权限的人发消息
                        $processId = $process['process_type'];
                        $orderTypeId = $orderInfo['order_type'];
                        $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 1);//1:查看;2:可写;3:分配;4:提交;5:转发;

                        //存入工单列表关联表
                        OrderEngine::importProcessSeeOrder($process, $privilegeIds);

                        //批量给所有角色发
                        foreach ($privilegeIds as $val) {
                            $data           = [
                                'company_id'=>$process['company_id'],  'privilege_id'=>$val,
                                'form_user_id'=>$userId, 'to_user_id'=>'',
                                'foreign_key'=>$foreignKey,
                                'type'=>9,'type_id'=>$process['id'],
                                'title'=>$orderInfo['order_title'],'content'=>$messageContent,
                                'theme'=>'工单详情调整'
                            ];
                            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
                        }
                    }

                    //更新优先采购信息
                    if(!empty($purchase_info)){
                        //先获取工单信息
                        $where = ['id'=> $process['order_id']];
                        $orderInfo = Order::where($where)->first()->toArray();
                        //获取相关订单信息
                        $customerOrderInfo = CustomerOrder::where('id','=',$orderInfo['customer_order_id'])->first()->toArray();
                        foreach($purchase_info as $val){
                            \App\Eloquent\Ygt\OrderMaterialPurchaseMark::updateOrCreate(
                                [
                                    'customer_order_pre_id'=>$customerOrderInfo['order_pre_id'],
                                    'customer_order_id'=>$orderInfo['customer_order_id'],
                                    'order_pre_id'=>$orderInfo['order_pre_id'],
                                    'material_id'=>$val['id'],
                                    'order_id'=>$process['order_id'],
                                ],
                                [
                                    'is_purchase'=>$val['is_purchase']
                                ]
                            );
                        }
                    }

                    return ['message'=>'修改成功'];
                }else{
                    return ['message'=>'没有做任何修改'];
                }
            }else{
                xThrow( ERR_UNKNOWN );
            }
        } else {
            // 组合字段和所填写内容
            $arr                = ['is_pre'=>'0','order_id'=>$process['order_id']];
            $result             = ProcessEngine::setDataByFieldType($process,$fieldList,$arr);


            //工序名称
            $processTitle = ygtProcess::getOneValueById($process['process_type'], 'title');

            //获得订单客户id
            $customerOrderInfo = Order::where('id','=',$process['order_id'])->first();
            $customerId = 0;
            if($customerOrderInfo){
                $customerOrderInfo = $customerOrderInfo->toArray();
                $customerId = $customerOrderInfo['customer_name'];
            }

            $re = [
                'create_order_title' => '工单工序信息',
                'process_title' => $processTitle,
                'process_field_list' => $result,
                'customer_id'=>$customerId,
                'button_title'=>"确认修改"
            ];
            return $re;
        }
    }
    //工序工单过程添加
    public function setCourse(){

        $userId                = Func::getHeaderValueByName( 'userid' );
        $orderProcessId       = request( 'id' );
        $finishNumber          = request( 'num' );
        if( !$orderProcessId || !$finishNumber ){
            xThrow( ERR_PARAMETER );
        }

        $where                  = ['user_id'=>$userId,'order_process_id'=>$orderProcessId];
        $inc_result             = OrderProcessCourse::incrementOneValue( $where, 'finish_number', $finishNumber );
        if( $inc_result ){
            $data               = ['user_id'=>$userId,'order_process_id'=>$orderProcessId, 'number'=>$finishNumber];
            $insertResult      = OrderProcessCourseLog::insertOneData( $data );
            if( $insertResult ){
                $result         = ['message'=>'工序工单过程添加成功'];
                return $result;
            } else {
                xThrow( ERR_UNKNOWN );
            }
        } else {
            xThrow( ERR_UNKNOWN );
        }
    }
}